package com.crealth.handler;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crealth.ConstantDefine;
import com.crealth.crmserver.CRMServerHandler;
import com.crealth.db.CompanyDb;
import com.crealth.db.ConsumerDb;
import com.crealth.db.ConsumerProductDb;
import com.crealth.db.LoanContractDb;
import com.crealth.db.UserDb;
import com.crealth.memcached.ConsumerCached;
import com.crealth.memcached.UserCached;
import com.crealth.model.CompanyModel;
import com.crealth.model.ConsumerInfoModel;
import com.crealth.model.ConsumerNextFollowupModel;
import com.crealth.model.UserModel;
import com.crealth.msg.NetMessageData;
import com.crealth.thread.ImportConsumerThread;
import com.crealth.utils.StringUtil;
import com.crealth.utils.Utils;

public class ConsumerInfoHandler {
	private static Logger logger = Logger.getLogger("running_log");
	private static Logger errorLog = Logger.getLogger("error_log");
	
	public static NetMessageData devClinetCommitInfo(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (!msgJson.containsKey("cliName") || !msgJson.containsKey("cliPhoneNum1")) {
			errorLog.error("devClinetCommitInfo  cliName or cliPhoneNum1 is null");
			resJson.put("resCode", ErrorCode.ERROR_NamePhone_Lenth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		String cliName = msgJson.getString("cliName");
		String phoneNum1 = msgJson.getString("cliPhoneNum1");
		if (cliName == null || cliName.length() == 0) {
			resJson.put("resCode", ErrorCode.ERROR_Name_Empty);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		if (phoneNum1 == null || phoneNum1.length() == 0) {
			resJson.put("resCode", ErrorCode.ERROR_Phone_Empty);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		if (phoneNum1.length() != 11) {
			resJson.put("resCode", ErrorCode.ERROR_Phone_Lenth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		Integer existID = ConsumerDb.selectConsumerInfoByPhone(userID, phoneNum1);
		if (existID != null && existID > 0) {
			resJson.put("resCode", ErrorCode.ERROR_DEVCLI_EXIST);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		boolean alreadyChengjiao = false;
		List<ConsumerInfoModel> phoneConsumerls = ConsumerDb.selectConsumerByPhoneNum(phoneNum1);
		for (ConsumerInfoModel tmpConsumer : phoneConsumerls) {
			String cliType = tmpConsumer.getCliType();
			if (cliType.indexOf("本人成交") >= 0 || cliType.indexOf("公司成交") >= 0 ||  
					tmpConsumer.getUserID() == userID ) {
				alreadyChengjiao = true;
				break;
			}
		}
		if (alreadyChengjiao) {
			resJson.put("resCode", ErrorCode.ERROR_Already_Chengjiao);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		int belongCompany = user.getBelongCompanyID();
		ConsumerInfoModel consumerModel = new ConsumerInfoModel();
		consumerModel.setUserID(userID); 
		consumerModel.setBelongCompany(belongCompany);
		consumerModel.parseFromJson(msgJson);
		consumerModel.setDevTime(new Timestamp(System.currentTimeMillis()));
		Integer consumerID = ConsumerCached.insertConsumerInfoObj(consumerModel);
		if (consumerID != null) {
			boolean needSendCS = false;
			if (consumerModel.getSubmitTm() != null) {
				ConsumerCached.updateConsumerFlowFollowByID(consumerID, ConsumerInfoModel.Flow_KF);
				needSendCS = true;
			}
			consumerModel = ConsumerCached.selectConsumer(consumerID);
			if (needSendCS) {
				sendSubmitComsumerToCS(user, consumerModel);
			}
			
			JSONObject infoJson = consumerModel.toJSONObject();
			resJson.put("resCode", 0);
			resJson.put("info", infoJson);
		}
		resJson.put("opUser", userID);
		sendMsg.setMsgBody(resJson.toJSONString());
		CRMServerHandler.sendMsgToLeader(revData.getMsgCmd(), user, sendMsg);
		sendMsg.setMsgCmd(revData.getMsgCmd());
		ResponseMsgQueue.sendBranchCompanyMgr(userID, user.getCompanyID(), sendMsg);
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		
		return sendMsg;
	}
	
	public static NetMessageData obtainClientDetailInfos(NetMessageData revData) {
		JSONObject msgJson = revData.getRevDataMsgJson();
		Integer userID = msgJson.getIntValue("id");				
		UserModel user = UserCached.selectUserByID(userID);
		int userPos = user.getPosition();
		List<ConsumerInfoModel> consumerls = null;
		int downMinid = Integer.MAX_VALUE;
		if (msgJson.containsKey("downMinId")) {
			downMinid = msgJson.getIntValue("downMinId");
		}
		if (Utils.isWindows()) {
			logger.info("downMinid: " + downMinid);
		}
		String strUnderlingIDs = null;
		if (ConstantDefine.Team_Manager == userPos || 
				ConstantDefine.Branch_Mgr == userPos || ConstantDefine.Branch_Mgr_Fu == userPos) {
			List<Integer> underlingIDs = UserDb.selectUnderlingIDs(userID);
			if ( underlingIDs.indexOf(userID) < 0 ) {
				underlingIDs.add(userID);
			}
			strUnderlingIDs = StringUtil.mergeListIntegerToString(underlingIDs, ",");
		}
		
		int msgCmd = NetMessageData.Net_Obtain_CliDetailInfos;
		List<Integer> consumerIDls = null;
		if (ConstantDefine.Sales_Man == userPos || ConstantDefine.Group_Leader == userPos ) {
			consumerIDls = ConsumerDb.selectConsumerIDByUserIDLimit(userID, downMinid);			
		}
		else if (ConstantDefine.Team_Manager == userPos || 
				ConstantDefine.Branch_Mgr == userPos || ConstantDefine.Branch_Mgr_Fu == userPos) {
			consumerIDls = ConsumerDb.selectConsumerIDByUserIDsLimit(strUnderlingIDs, downMinid);			
		}
		else if (ConstantDefine.Installmenter == userPos) {  //  按揭经理
			String mortgagerName = user.getUserName();
			List<Integer> contractIDs = ConsumerProductDb.selectContractIDsByMortgagerName(mortgagerName);
			if (contractIDs.size() > 0) {
				String strContractIDs = StringUtil.mergeListIntegerToString(contractIDs, ",");			
				consumerIDls = LoanContractDb.selectConsumerInfoIDByIDs(strContractIDs);
			}			
		}
		else if (ConstantDefine.InstallDpmMGR == userPos) {  // 按揭部经理
			consumerIDls = LoanContractDb.selectAllConsumerIDs();
		}
		else if (userPos >= ConstantDefine.Head_Manager) {
			consumerIDls = ConsumerDb.selectAllConsumerIDLimit(downMinid);
		}
		
		int arrNum = 0;
		if (consumerIDls == null || consumerIDls.size() == 0) {
			NetMessageData sendMsg = new NetMessageData();
			JSONObject resJson = new JSONObject();
			resJson.put("cnt", arrNum);
			sendMsg.setMsgBody(resJson.toJSONString());
			sendMsg.setUserID(userID);
			sendMsg.setMsgCmd(msgCmd);
			return sendMsg;
		}
		
		arrNum = consumerIDls.size();		
		JSONArray jsonArray = new JSONArray();
		List<Integer> curObtainIDs = new ArrayList<Integer>();
		for (int idx = 0; idx < consumerIDls.size(); ++idx) {			
			curObtainIDs.add(consumerIDls.get(idx));
			
			if (curObtainIDs.size() == 50 || idx == consumerIDls.size()-1) {
				user = UserCached.selectUserByID(userID);
				consumerls = ConsumerCached.getConsumerInfoByIDs(curObtainIDs);
				curObtainIDs.clear();
				for (ConsumerInfoModel model : consumerls) {
					UserModel belongUser = UserCached.selectUserByID( model.getUserID() );
					if (belongUser != null) {
						int consumerID = model.getId();
						int belongCompany = belongUser.getBelongCompanyID();
						ConsumerDb.updateBelongCompanyByID(consumerID, belongCompany);
					}
					JSONObject infoJson = model.toJSONObject();				
					jsonArray.add(infoJson);
				}
				NetMessageData sendMsg = new NetMessageData();
				JSONObject resJson = new JSONObject();
				resJson.put("infoArr", jsonArray);
				resJson.put("cnt", arrNum);
				//resJson.put("index", idx+1);
				String msgData = resJson.toJSONString();
				sendMsg.setMsgBody(msgData);
				ResponseMsgQueue.addMsgToQueue(msgCmd, userID, sendMsg);
				
				if (jsonArray.size() == 50) {
					jsonArray = new JSONArray();
				}
			}
		}
		
		return null;
	}
	
	public static NetMessageData modifyClinetInfo(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		Integer userID = msgJson.getInteger("id");
		UserModel user = UserCached.selectUserByID(userID);
		/*
		if (user.getPosition() != ConstantDefine.Installmenter
			&& user.getPosition() != ConstantDefine.Sales_Man) {
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		*/
		Integer consumerID = msgJson.getInteger("consumerID");
		if (consumerID == null || consumerID <= 0) {
			return null;
		}
		ConsumerInfoModel existModel = ConsumerCached.selectConsumer(consumerID);
		if (existModel == null) {
			resJson.put("resCode", ErrorCode.ERROR_NOT_CLIENT_EXIST);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		ConsumerInfoModel consumerModel = new ConsumerInfoModel();
		//consumerModel.setUserID(userID);
		consumerModel.parseFromJson(msgJson);
		consumerModel.setId(consumerID);
		if (consumerModel.getCliType().length() < 2) {
			consumerModel.setCliType(existModel.getCliType());
		}
		if (existModel.getCliType().indexOf("成交") > 0 && 
				consumerModel.getCliType().indexOf("成交") < 0) {
			consumerModel.setCliType(existModel.getCliType());
		}
		
		if (consumerModel.getName() == null || consumerModel.getPhoneNum1() == null ||
			consumerModel.getName().length() == 0 || consumerModel.getPhoneNum1().length() == 0) {
			errorLog.error("modifyClinetInfo  userID: " + userID + " name or phone is null");
			return null;
		}
		
		boolean needSendCS = false;
		int position = user.getPosition();
		if (position == ConstantDefine.Installmenter) {
			ConsumerCached.updateConsumerInfoObj(consumerModel, position);
		}
		else {
			//if (existModel.getStatus() >= ConsumerInfoModel.Contract_Saved) {
				//return null;
			//}
			if (consumerModel.getSubmitTm() != null
					&& consumerModel.getStatus() <= ConsumerInfoModel.Submit_Already) {
				consumerModel.setStatus(ConsumerInfoModel.Submit_Already);
			} else {
				consumerModel.setStatus(existModel.getStatus());
			}
			
			Integer res = ConsumerCached.updateConsumerInfoObj(consumerModel, position);
			Timestamp submitTm = consumerModel.getSubmitTm();
			Timestamp todayTm = Utils.getTodayTimestamp();
			if (submitTm != null && submitTm.after(todayTm)) {
				needSendCS = true;
				ConsumerCached.updateConsumerFlowFollowByID(consumerID, ConsumerInfoModel.Flow_KF);
			}
			if (res == null) {
				resJson.put("resCode", ErrorCode.ERROR_SERVICE_ERROR);
				sendMsg.setMsgBody(resJson.toJSONString());
				return sendMsg;
			}
		}
		
		if (position > ConstantDefine.Branch_Mgr_Fu || 
				position == ConstantDefine.InstallDpmMGR ) {
			if (!consumerModel.getName().equals(existModel.getName()) || 
				!consumerModel.getPhoneNum1().equals(existModel.getPhoneNum1())) {
				ConsumerCached.updateConsumerNameAndPhone(consumerID, 
						consumerModel.getName(), 
						consumerModel.getPhoneNum1() );
			}
		}
		
		consumerModel = ConsumerCached.selectConsumer(consumerID);
		int belongSalesManID = existModel.getUserID();
		UserModel belongUser = UserCached.selectUserByID(belongSalesManID);
		if (needSendCS) {
			sendSubmitComsumerToCS(belongUser, consumerModel);
		}
		if (consumerModel != null) {
			JSONObject infoJson = consumerModel.toJSONObject();
			resJson.put("resCode", 0);
			resJson.put("info", infoJson);
		}
		resJson.put("opUser", userID);
		sendMsg.setMsgBody(resJson.toJSONString());
		sendMsg.setMsgCmd(revData.getMsgCmd());
		
		if (userID != belongSalesManID) {
			ResponseMsgQueue.addMsgToQueue(revData.getMsgCmd(), belongSalesManID, sendMsg);
		}		
		if (belongUser != null) {
			int leaderID = belongUser.getLeaderID();
			if (leaderID > 0 && userID != leaderID) {
				ResponseMsgQueue.addMsgToQueue(revData.getMsgCmd(), leaderID, sendMsg);
			}
			int companyID = belongUser.getBelongCompanyID();
			ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);
		}
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		
		return sendMsg;
	}
	
	public static NetMessageData commitLeaderGuide(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		Integer userID = msgJson.getInteger("id");
		if (userID == null || userID <= 0) {
			return null;
		}
		Integer consumerID = msgJson.getInteger("consumerID");
		if (consumerID == null || consumerID <= 0) {
			resJson.put("resCode", ErrorCode.ERROR_ConsumerID);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() < ConstantDefine.Team_Manager) {
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		int cliLevel = msgJson.getIntValue("cliLevel");
		String strGuide = msgJson.getString("guide");
		String strMemo = msgJson.getString("leaderMemo");
		ConsumerInfoModel model = new ConsumerInfoModel();
		model.setId(consumerID);
		model.setCliLevel(cliLevel);
		model.setLeaderGuide(strGuide.trim());
		model.setLeaderMemo(strMemo.trim());		
		if (msgJson.containsKey("meetTalkTm")) {
			long meetTalkTm = msgJson.getLongValue("meetTalkTm");
			model.setMeetTalkTm(new Timestamp(meetTalkTm*1000));
		}
		else {
			model.setMeetTalkTm(null);
		}			
		
		Integer res = ConsumerCached.updateConsumerLeaderGuideByID(model);
		if (res == null) {
			resJson.put("resCode", ErrorCode.ERROR_SERVICE_ERROR);
			sendMsg.setMsgBody(resJson.toJSONString());			
			return sendMsg;
		}
		
		boolean needNameJson = false;
		/*
		if (msgJson.containsKey("cliName") && msgJson.containsKey("cliPhoneNum1")) {
			String strName = msgJson.getString("cliName");
			String phoneNum1 = msgJson.getString("cliPhoneNum1");
			if (strName.length() > 0 && phoneNum1.length() > 0 && phoneNum1.length() == 11) {
				ConsumerCached.updateConsumerNameAndPhone(consumerID, strName, phoneNum1);
				needNameJson = true;
			}
		}*/
		
		model = ConsumerDb.selectConsumerLeaderGuideByID(consumerID);
		int belongUserID = model.getUserID();
		JSONObject guiedeJson = model.toLeaderGuideJSON(needNameJson);
		guiedeJson.put("leaderMemo", model.getLeaderMemo());
		resJson.put("leaderGuide", guiedeJson);
		resJson.put("resCode", 0);
		resJson.put("opUser", userID);
		sendMsg.setMsgBody(resJson.toJSONString());
		sendMsg.setMsgCmd(NetMessageData.Net_Modify_LeaderGuide);
		
		if (belongUserID == 0) {
			return sendMsg;
		}
		
		NetMessageData sendMsg2 = new NetMessageData();
		JSONObject resJson2 = new JSONObject();
		JSONObject guiedeJson2 = model.toLeaderGuideJSON(needNameJson);
		resJson2.put("leaderGuide", guiedeJson2);
		resJson2.put("resCode", 0);
		resJson2.put("opUser", userID);
		sendMsg2.setMsgBody(resJson2.toJSONString());
		ResponseMsgQueue.addMsgToQueue(NetMessageData.Net_Modify_LeaderGuide, belongUserID, sendMsg2);
			
		UserModel salesMan = UserCached.selectUserByID(belongUserID);
		if (salesMan != null) {
			int companyID = salesMan.getCompanyID();
			if (userID != salesMan.getLeaderID()) {
				ResponseMsgQueue.addMsgToQueue(NetMessageData.Net_Modify_LeaderGuide, salesMan.getLeaderID(), sendMsg);
			}
			ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);
			ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		}
		
		return sendMsg;
	}
	
	public static NetMessageData importPurposeClinetInfo(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		if (userID <= 0) {
			return null;
		}
		String cliName = msgJson.getString("cliName");
		String phoneNum1 = msgJson.getString("cliPhoneNum1");
		if (cliName == null || phoneNum1 == null) {
			return null;
		}
		cliName = cliName.trim();
		phoneNum1 = phoneNum1.trim();
		if (cliName.length() == 0 || phoneNum1.length() < 5) {
			return null;
		}
		Integer existID = ConsumerDb.selectConsumerInfoByNameAndPhone(userID, cliName, phoneNum1);
		if (existID != null) {
			errorLog.error("has exit cliName: "+cliName+"  phoneNum1:"+phoneNum1);
			resJson.put("resCode", ErrorCode.ERROR_DEVCLI_EXIST);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		ConsumerInfoModel consumerModel = new ConsumerInfoModel();
		consumerModel.setUserID(userID);
		consumerModel.parseImportPurposeFromJson(msgJson);
		Integer consumerID = ConsumerDb.insertImportPurposeExcel(consumerModel);
		if (consumerID != null && consumerID > 0) {
			consumerModel = ConsumerCached.selectConsumer(consumerID);
			JSONObject infoJson = consumerModel.toJSONObject();
			resJson.put("resCode", 0);
			resJson.put("addFrom", "excelPurpose");
			resJson.put("info", infoJson);
		}		
		sendMsg.setMsgBody(resJson.toJSONString());		
		//CRMServerHandler.sendMsgToLeader(revData.getMsgCmd(), userID, sendMsg);
		return sendMsg;		
	}
	
	public static NetMessageData syncClientDetailInfos(NetMessageData revData) {
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		if (userID <= 0) {
			return null;
		}
		
		Integer userPos = UserDb.selectUserPosition(userID);
		if (userPos == null) {
			return null;
		}
		long localTm = 0;
		if (msgJson.containsKey("localDataTm")) {
			localTm = msgJson.getLongValue("localDataTm");
		}
		List<ConsumerInfoModel> consumerls = null;
		localTm = localTm * 1000;
		Timestamp tm = new Timestamp(localTm);
		if (ConstantDefine.Sales_Man == userPos || ConstantDefine.Group_Leader == userPos ) {
			consumerls = ConsumerDb.selectConsumerInfoByUserIDTm(userID, tm);
		}
		else if (ConstantDefine.Team_Manager == userPos 
				|| ConstantDefine.Branch_Mgr == userPos || ConstantDefine.Branch_Mgr_Fu == userPos) {
			List<Integer> underlingIDs = UserDb.selectUnderlingIDs(userID);
			underlingIDs.add(userID);
			String strIDs = StringUtil.mergeListIntegerToString(underlingIDs, ",");
			consumerls = ConsumerDb.selectConsumerInfoByUserIDsTm(strIDs, tm);
		}
		else if (userPos >= ConstantDefine.Head_Manager) {
			consumerls = ConsumerDb.selectAllConsumerInfoTm(tm);
		}
		
		int arrNum = 0;		
		if (consumerls == null || consumerls.size() == 0) {
			NetMessageData sendMsg = new NetMessageData();
			JSONObject resJson = new JSONObject();
			resJson.put("cnt", arrNum);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		boolean isLeader = false;		
		if (userPos >= ConstantDefine.Team_Manager) {
			isLeader = true;
		}		
		NetMessageData sendMsg = new NetMessageData();
		arrNum = consumerls.size();
		JSONArray jsonArray = new JSONArray();
		for (int idx = 0; idx < consumerls.size(); ++idx) {
			ConsumerInfoModel model = consumerls.get(idx);
			JSONObject infoJson = model.toJSONObject();
			if (isLeader) {
				infoJson.put("leaderMemo", model.getLeaderMemo());
			}
			
			int cmd = revData.getMsgCmd();
			jsonArray.add(infoJson);
			if (jsonArray.size() == 30 || idx == consumerls.size()-1) {
				JSONObject resJson = new JSONObject();
				resJson.put("infoArr", jsonArray);
				resJson.put("cnt", arrNum);
				resJson.put("index", idx+1);
				sendMsg.setMsgBody(resJson.toJSONString());
				ResponseMsgQueue.addMsgToQueue(cmd, userID, sendMsg);
				if (jsonArray.size() == 30) {
					jsonArray = new JSONArray();
				}
			}
		}
		
		return null;
	}
	
	public static NetMessageData dispatchPurpose(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		Integer userID = msgJson.getInteger("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() < ConstantDefine.Team_Manager) {
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		int toUser = msgJson.getIntValue("toUser");
		String purposeIDs = msgJson.getString("purposeIDs");
		if (purposeIDs == null || purposeIDs.length() == 0) {
			return null;
		}
		String strIDArr[] = purposeIDs.split(",");
		String successIDs = "";
		int successCnt = 0;  // 分配成功的数量
		int failCnt = 0;  // 失败的数量
		Set<Integer> consumerCompany = new HashSet<Integer>();
		JSONArray jsonArray = new JSONArray();
		for (String strid : strIDArr) {
			int id = Integer.valueOf(strid);
			String setCliType = ConstantDefine.getConsumerTypeName(10);
			ConsumerInfoModel consumerInfo = ConsumerCached.selectConsumer(id);
			if (consumerInfo == null) {
				errorLog.error("dispatchPurpose 562 consumerInfo is null consumer ID: " + strid);
				continue;
			}
				
			String phoneNum = consumerInfo.getPhoneNum1();
			List<ConsumerInfoModel> existConsumerls = ConsumerDb.selectUserConsumerByPhoneNum(toUser, phoneNum);
			if (existConsumerls != null && existConsumerls.size() > 0) {
				failCnt++;
				continue;
			}
			UserModel consumerUser = UserCached.selectUserByID(consumerInfo.getUserID());
			if (consumerUser != null) {
				consumerCompany.add(consumerUser.getCompanyID());
			}
			String strcliType = consumerInfo.getCliType();
			if (strcliType.indexOf("本人成交") >= 0) {
				setCliType = ConstantDefine.getConsumerTypeName(12);
			} else if (strcliType.indexOf("公司成交") >= 0) {
				setCliType = strcliType;
			} else {
				setCliType = ConstantDefine.getConsumerTypeName(10);
			}
			consumerInfo.setCliType(setCliType);
			
			Integer res = ConsumerCached.updateConsumerUserByID(id, toUser, setCliType);
			if (res != null && res >= 1) {
				successCnt++;
				if (successIDs.length() == 0) {
					successIDs = "" + id;
				}
				else {
					successIDs += "," + id;
				}
				jsonArray.add(consumerInfo.toJSONObject());
			}
		}
		
		resJson.put("successIDs", successIDs);
		resJson.put("toUser", toUser);
		resJson.put("resCode", 0);
		resJson.put("opUserID", userID);
		resJson.put("successCnt", successCnt);
		resJson.put("failCnt", failCnt);
		int cmd = revData.getMsgCmd();
		sendMsg.setMsgBody(resJson.toJSONString());
		sendMsg.setMsgCmd(cmd);
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		ResponseMsgQueue.sendMsgToSalesMan(userID, sendMsg);
		for (Integer curCompanyID : consumerCompany) {
			ResponseMsgQueue.sendBranchCompanyMgr(userID, curCompanyID, sendMsg);
		}
		
		NetMessageData sendMsg2 = new NetMessageData();
		JSONObject resJson2 = new JSONObject();
		resJson2.put("consumerInfoArr", jsonArray);
		resJson2.put("toUser", toUser);
		resJson2.put("resCode", 0);
		resJson2.put("opUserID", userID);
		resJson2.put("successCnt", successCnt);
		resJson2.put("failCnt", failCnt);
		resJson2.put("successIDs", successIDs);
		sendMsg2.setMsgBody(resJson2.toJSONString());
		sendMsg2.setMsgCmd(cmd);
		ResponseMsgQueue.addMsgToQueue(cmd, toUser, sendMsg2);
		UserModel salesMan = UserCached.selectUserByID(toUser);
		if (salesMan != null && salesMan.getLeaderID() > 0 && 
				userID != salesMan.getLeaderID()) {
			ResponseMsgQueue.addMsgToQueue(cmd, salesMan.getLeaderID(), sendMsg2);
		}
		
		int companyID = salesMan.getBelongCompanyID();		
		ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg2);
		
		return sendMsg;
	}
	
	public static NetMessageData copyPurpose(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		Integer userID = msgJson.getInteger("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() < ConstantDefine.Branch_Mgr_Fu) {
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		int toUser = msgJson.getIntValue("toUser");
		UserModel toUserObj = UserCached.selectUserByID(toUser);
		if (toUserObj.getPosition() != ConstantDefine.Sales_Man && 
			toUserObj.getPosition() != ConstantDefine.Group_Leader ) {
			resJson.put("resCode", ErrorCode.ERROR_NOT_SALESMAN);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		JSONArray jsonArray = new JSONArray();
		String purposeIDs = msgJson.getString("purposeIDs");
		if (purposeIDs == null || purposeIDs.length() == 0) {
			return null;
		}
		List<ConsumerInfoModel> consumerls = ConsumerDb.selectConsumerByIDs(purposeIDs);
		for (ConsumerInfoModel model : consumerls) {
			model.setUserID(toUser);
			model.setId(0);
			//model.setFollowupls(null);
			String phoneNum = model.getPhoneNum1();
			List<ConsumerInfoModel> existConsumerls = ConsumerDb.selectUserConsumerByPhoneNum(toUser, phoneNum);
			if (existConsumerls != null && existConsumerls.size() > 0) {
				continue;
			}
			
			/*String strcliType = model.getCliType();
			if (strcliType.indexOf("本人成交") >= 0) {
				model.setCliType(ConstantDefine.getConsumerTypeName(12));
			} else if (strcliType.indexOf("公司成交") >= 0) {
			} else {
				model.setCliType(ConstantDefine.getConsumerTypeName(10));
			}*/
			ConsumerDb.insertConsumerInfoObj(model);
			if (model.getId() > 0) {
				jsonArray.add(model.toJSONObject());
			}
		}
		
		resJson.put("info", jsonArray);
		resJson.put("cnt", jsonArray.size());
		resJson.put("resCode", 0);
		resJson.put("opUserID", userID);
		sendMsg.setMsgBody(resJson.toJSONString());
		
		int cmd = revData.getMsgCmd();
		sendMsg.setMsgCmd(cmd);		
		ResponseMsgQueue.addMsgToQueue(cmd, toUser, sendMsg);
		int companyID = toUserObj.getBelongCompanyID();
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);
		if (toUserObj != null && toUserObj.getLeaderID() != userID) {
			ResponseMsgQueue.addMsgToQueue(cmd, toUserObj.getLeaderID(), sendMsg);
		}
		
		return sendMsg;
	}
	
	public static NetMessageData obtainMeetTalkPurpose(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();		
		JSONObject msgJson = revData.getRevDataMsgJson();
		Integer userID = msgJson.getInteger("id");
		UserModel user = UserCached.selectUserByID(userID);
		int userPos = user.getPosition();
		Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);		
		Timestamp curDayTimestamp = new Timestamp(cal.getTimeInMillis());
		String strUnderlingIDs = null;
		List<ConsumerInfoModel> consumerls = null;
		if (ConstantDefine.Branch_Mgr == userPos || 
			ConstantDefine.Branch_Mgr_Fu == userPos || 
			(ConstantDefine.Customer_Service == userPos && !user.isTopCompany() ) ) {
			List<Integer> underlingIDs = UserDb.selectUnderlingIDs(userID);
			if (underlingIDs.indexOf(userID) < 0) {
				underlingIDs.add(userID);
			}
			strUnderlingIDs = StringUtil.mergeListIntegerToString(underlingIDs, ",");
			consumerls = ConsumerDb.selectMeetTalkPurpose(strUnderlingIDs, curDayTimestamp);
		}
		else if (userPos >= ConstantDefine.Head_Manager || user.isTopCompany() ) {
			consumerls = ConsumerDb.selectAllMeetTalkPurpose(curDayTimestamp);
		}
		if (consumerls == null) {
			return null;
		}		
		int arrNum = consumerls.size();
		
		if (arrNum > 0) {
			int cmd = revData.getMsgCmd();
			JSONArray jsonArray = new JSONArray();
			for (int idx = 0; idx < arrNum; ++idx) {
				ConsumerInfoModel model = consumerls.get(idx);
				jsonArray.add(model.toMeetTalkJSONObject());
				if (jsonArray.size() == 50 || idx == arrNum-1) {
					JSONObject resJson = new JSONObject();
					resJson.put("num", arrNum);
					resJson.put("infoArr", jsonArray);
					sendMsg.setMsgBody(resJson.toJSONString());			
					ResponseMsgQueue.addMsgToQueue(cmd, userID, sendMsg);
					
					if (jsonArray.size() == 50) {
						jsonArray = new JSONArray();
					}
				}
			}			
		}
		
		return null;
	}
	
	private static void sendSubmitComsumerToCS(UserModel user, ConsumerInfoModel consumerInfo) {
		NetMessageData sendcsMsg = new NetMessageData();
		JSONObject rescsJson = new JSONObject();
		rescsJson.put("resCode", 0);
		rescsJson.put("info", consumerInfo.toMeetTalkJSONObject());
		sendcsMsg.setMsgBody(rescsJson.toJSONString());
		sendcsMsg.setMsgCmd(NetMessageData.Net_Submit_Consumer_Noti);
		
		int belongComID = user.getBelongCompanyID();
		ResponseMsgQueue.sendMsgToCustomerService(0, belongComID, sendcsMsg);
	}
	
	public static NetMessageData saveConsumerNextFollowup(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		//Integer userID = msgJson.getInteger("id");
		int consumerID = msgJson.getIntValue("consumerID");
		if (consumerID <= 0) {
			return null;
		}
		String strNextFollowup = msgJson.getString("nextFollowupArr");
		JSONArray jsonArr = JSONArray.parseArray(strNextFollowup);
		JSONArray resJsonArr = new JSONArray();
		for (int i = 0; i < jsonArr.size(); ++i) {
			JSONObject jsonObj = jsonArr.getJSONObject(i);
			ConsumerNextFollowupModel nextFollow = new ConsumerNextFollowupModel();
			nextFollow.parseFromJson(jsonObj);
			nextFollow.setConsumerID(consumerID);
			if (nextFollow.getId() <= 0) {
				ConsumerDb.insertNextFollowup(nextFollow);
			} else {
				ConsumerDb.updateNextFollowup(nextFollow);
			}
			resJsonArr.add(nextFollow.toJSONObject());
		}
		ConsumerCached.deleteConsumerCached(consumerID);
		
		resJson.put("resCode", 0);
		resJson.put("consumerID", consumerID);
		resJson.put("nextFollowupArr", resJsonArr);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData deleteConsumerNextFollowup(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int nextFollowupID = msgJson.getIntValue("nextFollowupID");
		int consumerID = msgJson.getIntValue("consumerID");
		Integer res = ConsumerDb.deleteNextFollowup(nextFollowupID);
		if (res != null && res == 1) {
			resJson.put("nextFollowupID", nextFollowupID);
			resJson.put("consumerID", consumerID);
			ConsumerCached.deleteConsumerCached(consumerID);
		}
		
		resJson.put("resCode", 0);		
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	//  上传  意向客户
	public static NetMessageData uploadConsumerInfo(NetMessageData revData) {		
		//NetMessageData sendMsg = new NetMessageData();
		//JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			errorLog.error("uploadConsumerInfo msgJson is null");
			return null;
		}
		int userID = msgJson.getIntValue("id");
		String dtype = msgJson.getString("dtype");
		String data = msgJson.getString("data");
		String fileName = msgJson.getString("fileName");
		String fileDir = "./uploadData/";
		String osName = Utils.getOSName();
		Utils.checkAndCreateDir(fileDir);
		if (osName.startsWith("Window")) {
		}
		else {
			File f = new File(fileDir);
	        f.setWritable(true, false);						
		}		
		Utils.saveUploadFile(userID, dtype, data, 
				fileName,  fileName, fileDir);
		
		ImportConsumerThread importThread = new ImportConsumerThread(fileName, userID);
		if (msgJson.containsKey("fieldMap")) {
			JSONObject fieldMapJson = msgJson.getJSONObject("fieldMap");
			importThread.setFieldMapJson(fieldMapJson);
		}
		importThread.start();
		
		return null;
	}
	
	//  删除意向客户
	public static NetMessageData deleteConsumer(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		Integer userID = msgJson.getInteger("id");
		String purposeIDs = msgJson.getString("purposeIDs");
		if (purposeIDs == null || purposeIDs.length() == 0) {
			resJson.put("resCode", ErrorCode.ERROR_DEL_CONSUMER_NULL);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		List<Integer> contractConsumerIDs = LoanContractDb.selectHasContractConsumerID(purposeIDs);
		if (contractConsumerIDs != null && contractConsumerIDs.size() > 0) {
			for (Integer consumerID : contractConsumerIDs) {
				String strID = "" + consumerID + ",";
				purposeIDs = purposeIDs.replaceAll(strID, "");
				strID = "" + consumerID;
				purposeIDs = purposeIDs.replaceAll(strID, "");
			}
		}
		purposeIDs = purposeIDs.trim();
		if (purposeIDs.length() == 0) {
			resJson.put("resCode", ErrorCode.ERROR_DEL_CSMHASCONTRACT);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		Integer res = ConsumerDb.updateConsumerDeleteByIDs(purposeIDs);
		String delConsumerIDs = "";
		if (res != null && res > 0) {			
			List<Integer> consumerIDls = StringUtil.splitStringToIntegerList(purposeIDs, ",");
			for (Integer curID : consumerIDls) {
				ConsumerCached.deleteConsumerCached(curID);
				if (delConsumerIDs.length() > 0) {
					delConsumerIDs += ",";
				}
				delConsumerIDs += curID;
			}
		}
		
		resJson.put("opUser", userID);
		resJson.put("resCode", 0);
		resJson.put("delConsumerIDs", delConsumerIDs);
		sendMsg.setMsgBody(resJson.toJSONString());
		
		int cmd = revData.getMsgCmd();
		sendMsg.setMsgCmd(cmd);		
		ResponseMsgQueue.sendMsgToSalesMan(userID, sendMsg);
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		List<CompanyModel> allCompanyls = CompanyDb.selectAllCompany();
		for (CompanyModel curCompany : allCompanyls) {
			if (curCompany.getCompanyAddr().length() > 0) {
				ResponseMsgQueue.sendBranchCompanyMgr(userID, curCompany.getId(), sendMsg);
			}
		}
		
		return sendMsg;
	}
	
	
	
}
